<!-- 安全防护演示页面 - 展示XSS和CSRF防护功能 -->
<template>
    <div class="security-page">
        <AppHeader />
        <main class="security-container">
            <!-- 页面标题 -->
            <div class="page-header">
                <h1 class="page-title">安全防护演示</h1>
                <p class="page-description">
                    展示博客系统的安全防护功能，包括XSS防护、CSRF防护、输入验证等安全措施
                </p>
            </div>

            <!-- XSS防护演示区域 -->
            <div class="security-section">
                <div class="section-header">
                    <el-icon class="section-icon">
                        <Warning />
                    </el-icon>
                    <div class="section-content">
                        <h2 class="section-title">XSS防护演示</h2>
                        <p class="section-description">
                            演示HTML内容净化和字符转义功能，防止跨站脚本攻击
                        </p>
                    </div>
                </div>

                <div class="demo-content">
                    <div class="input-group">
                        <label>输入内容（包含恶意脚本）:</label>
                        <el-input v-model="xssInput" type="textarea" :rows="4" placeholder="输入包含恶意脚本的内容..."
                            @input="handleXSSInput" />
                    </div>

                    <div class="result-group">
                        <div class="result-item">
                            <h4>净化后的HTML:</h4>
                            <div class="result-content" v-html="sanitizedHtml"></div>
                        </div>
                        <div class="result-item">
                            <h4>转义后的文本:</h4>
                            <div class="result-content">{{ escapedHtml }}</div>
                        </div>
                    </div>

                    <div class="action-buttons">
                        <el-button @click="testXSSAttack" type="warning">
                            测试XSS攻击
                        </el-button>
                        <el-button @click="testSafeHtml" type="success">
                            测试HTML净化
                        </el-button>
                        <el-button @click="testEscapeHtml" type="info">
                            测试字符转义
                        </el-button>
                    </div>
                </div>
            </div>

            <!-- CSRF防护演示区域 -->
            <div class="security-section">
                <div class="section-header">
                    <el-icon class="section-icon">
                        <Lock />
                    </el-icon>
                    <div class="section-content">
                        <h2 class="section-title">CSRF防护演示</h2>
                        <p class="section-description">
                            演示CSRF Token的生成、验证和管理功能
                        </p>
                    </div>
                </div>

                <div class="demo-content">
                    <div class="csrf-info">
                        <div class="info-item">
                            <strong>当前Token:</strong>
                            <span class="token-display">{{ currentCSRFToken || '未生成' }}</span>
                        </div>
                        <div class="info-item">
                            <strong>状态:</strong>
                            <el-tag :type="isTokenValid ? 'success' : 'danger'">
                                {{ isTokenValid ? '有效' : '无效' }}
                            </el-tag>
                        </div>
                        <div class="info-item" v-if="tokenExpiry">
                            <strong>过期时间:</strong>
                            <span>{{ tokenExpiry }}</span>
                        </div>
                    </div>

                    <div class="result-group">
                        <div class="result-item">
                            <h4>操作结果:</h4>
                            <el-alert :title="csrfResult.message" :type="csrfResult.type" :closable="false"
                                v-if="csrfResult.message" />
                        </div>
                    </div>

                    <div class="action-buttons">
                        <el-button @click="generateCSRFToken" type="primary">
                            生成Token
                        </el-button>
                        <el-button @click="validateCSRFToken" type="success">
                            验证Token
                        </el-button>
                        <el-button @click="clearCSRFToken" type="danger">
                            清除Token
                        </el-button>
                    </div>
                </div>
            </div>

            <!-- 输入验证演示区域 -->
            <div class="security-section">
                <div class="section-header">
                    <el-icon class="section-icon">
                        <Check />
                    </el-icon>
                    <div class="section-content">
                        <h2 class="section-title">输入验证演示</h2>
                        <p class="section-description">
                            演示各种输入字段的验证规则和实时验证功能
                        </p>
                    </div>
                </div>

                <div class="demo-content">
                    <div class="validation-forms">
                        <div class="form-group">
                            <label>用户名:</label>
                            <el-input v-model="validationInputs.username" placeholder="请输入用户名"
                                @input="validateUsername" />
                            <div class="validation-message" :class="{ error: !usernameValid, success: usernameValid }">
                                {{ usernameMessage }}
                            </div>
                        </div>

                        <div class="form-group">
                            <label>邮箱:</label>
                            <el-input v-model="validationInputs.email" placeholder="请输入邮箱地址" @input="validateEmail" />
                            <div class="validation-message" :class="{ error: !emailValid, success: emailValid }">
                                {{ emailMessage }}
                            </div>
                        </div>

                        <div class="form-group">
                            <label>密码:</label>
                            <el-input v-model="validationInputs.password" type="password" placeholder="请输入密码"
                                @input="validatePassword" />
                            <div class="validation-message" :class="{ error: !passwordValid, success: passwordValid }">
                                {{ passwordMessage }}
                            </div>
                        </div>

                        <div class="form-group">
                            <label>网址:</label>
                            <el-input v-model="validationInputs.url" placeholder="请输入网址" @input="validateUrl" />
                            <div class="validation-message" :class="{ error: !urlValid, success: urlValid }">
                                {{ urlMessage }}
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 安全工具演示区域 -->
            <div class="security-section">
                <div class="section-header">
                    <el-icon class="section-icon">
                        <Tools />
                    </el-icon>
                    <div class="section-content">
                        <h2 class="section-title">安全工具演示</h2>
                        <p class="section-description">
                            演示各种安全工具函数的使用
                        </p>
                    </div>
                </div>

                <div class="demo-content">
                    <div class="tools-grid">
                        <div class="tool-item">
                            <h4>随机字符串生成</h4>
                            <div class="tool-content">
                                <el-input v-model="secureRandom" readonly />
                                <el-button @click="generateRandom" type="primary">
                                    生成随机字符串
                                </el-button>
                            </div>
                        </div>

                        <div class="tool-item">
                            <h4>文件名安全检查</h4>
                            <div class="tool-content">
                                <el-input v-model="filenameInput" placeholder="输入文件名" @input="checkFilename" />
                                <div class="result-display">
                                    <strong>安全文件名:</strong>
                                    <span>{{ safeFilename }}</span>
                                </div>
                            </div>
                        </div>

                        <div class="tool-item">
                            <h4>JSON安全解析</h4>
                            <div class="tool-content">
                                <el-input v-model="jsonInput" type="textarea" :rows="3" placeholder="输入JSON字符串"
                                    @input="parseJson" />
                                <div class="result-display">
                                    <strong>解析结果:</strong>
                                    <pre>{{ jsonResult }}</pre>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 安全建议区域 -->
            <div class="security-section">
                <div class="section-header">
                    <el-icon class="section-icon">
                        <InfoFilled />
                    </el-icon>
                    <div class="section-content">
                        <h2 class="section-title">安全建议</h2>
                        <p class="section-description">
                            提供Web安全的最佳实践和建议
                        </p>
                    </div>
                </div>

                <div class="demo-content">
                    <div class="security-tips">
                        <div class="tip-item">
                            <h4>XSS防护建议:</h4>
                            <ul>
                                <li>始终对用户输入进行HTML净化</li>
                                <li>使用DOMPurify等专业库进行内容过滤</li>
                                <li>对输出内容进行适当的字符转义</li>
                                <li>设置严格的CSP（内容安全策略）</li>
                            </ul>
                        </div>

                        <div class="tip-item">
                            <h4>CSRF防护建议:</h4>
                            <ul>
                                <li>为所有敏感操作生成CSRF Token</li>
                                <li>在请求头中包含Token进行验证</li>
                                <li>设置合理的Token过期时间</li>
                                <li>使用SameSite Cookie属性</li>
                            </ul>
                        </div>

                        <div class="tip-item">
                            <h4>输入验证建议:</h4>
                            <ul>
                                <li>在客户端和服务器端都进行验证</li>
                                <li>使用正则表达式进行格式验证</li>
                                <li>限制输入长度和字符类型</li>
                                <li>对特殊字符进行转义处理</li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </main>
        <AppFooter />
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Lock, Check, Tools, InfoFilled, Warning } from '@element-plus/icons-vue'
import AppHeader from '../components/AppHeader.vue'
import AppFooter from '../components/AppFooter.vue'
import {
    sanitizeHtml,
    escapeHtml,
    validateInput,
    csrfProtection,
    validateField,
    VALIDATION_RULES,
    generateSecureRandom,
    safeJsonParse,
    getSafeFilename
} from '../utils/security'

// ==================== 响应式数据 ====================

// XSS防护相关数据
const xssInput = ref('&lt;script&gt;alert("XSS攻击")&lt;/script&gt;&lt;p&gt;这是安全的内容&lt;/p&gt;')
const sanitizedHtml = ref('')
const escapedHtml = ref('')

// CSRF防护相关数据
const currentCSRFToken = ref('')
const isTokenValid = ref(false)
const tokenExpiry = ref('')
const csrfResult = reactive({
    type: '',
    message: ''
})

// 输入验证相关数据
const validationInputs = reactive({
    username: '',
    email: '',
    password: '',
    url: ''
})

const usernameValid = ref(false)
const emailValid = ref(false)
const passwordValid = ref(false)
const urlValid = ref(false)

const usernameMessage = ref('')
const emailMessage = ref('')
const passwordMessage = ref('')
const urlMessage = ref('')

// 安全工具相关数据
const secureRandom = ref('')
const filenameInput = ref('')
const safeFilename = ref('')
const jsonInput = ref('')
const jsonResult = ref('')

// ==================== 计算属性 ====================

/**
* 计算CSRF Token状态
*/
const csrfStatus = computed(() => {
    return {
        token: currentCSRFToken.value,
        valid: isTokenValid.value,
        expiry: tokenExpiry.value
    }
})

// ==================== 方法函数 ====================

/**
* 处理XSS输入变化
* @description 当用户输入变化时，实时更新防护结果
*/
const handleXSSInput = () => {
    sanitizedHtml.value = sanitizeHtml(xssInput.value)
    escapedHtml.value = escapeHtml(xssInput.value)
}

/**
* 测试XSS攻击
* @description 演示常见的XSS攻击向量
*/
const testXSSAttack = () => {
    const attackVectors = [
        '&lt;script&gt;alert("XSS")&lt;/script&gt;',
        '&lt;img src="x" onerror="alert(\'XSS\')"&gt;',
        '&lt;svg onload="alert(\'XSS\')"&gt;',
        'javascript:alert("XSS")',
        '&lt;iframe src="javascript:alert(\'XSS\')"&gt;&lt;/iframe&gt;'
    ]

    const randomAttack = attackVectors[Math.floor(Math.random() * attackVectors.length)]
    xssInput.value = randomAttack + '&lt;p&gt;这是正常内容&lt;/p&gt;'
    handleXSSInput()

    ElMessage.info('已注入恶意脚本，请查看防护效果')
}

/**
* 测试HTML净化
* @description 演示HTML净化功能
*/
const testSafeHtml = () => {
    xssInput.value = '&lt;script&gt;alert("危险")&lt;/script&gt;&lt;p&gt;安全内容&lt;/p&gt;&lt;img src="x" onerror="alert(\'XSS\')"&gt;'
    handleXSSInput()
    ElMessage.success('HTML净化完成，恶意脚本已被移除')
}

/**
* 测试字符转义
* @description 演示HTML字符转义功能
*/
const testEscapeHtml = () => {
    xssInput.value = '&lt;script&gt;alert("转义测试")&lt;/script&gt;&lt;p&gt;内容&lt;/p&gt;'
    handleXSSInput()
    ElMessage.success('字符转义完成，特殊字符已被转义')
}

/**
* 生成CSRF Token
* @description 生成新的CSRF Token并更新状态
*/
const generateCSRFToken = () => {
    const token = csrfProtection.generateToken()
    currentCSRFToken.value = token
    isTokenValid.value = true
    tokenExpiry.value = new Date(Date.now() + 24 * 60 * 60 * 1000).toLocaleString()

    csrfResult.type = 'success'
    csrfResult.message = 'CSRF Token生成成功'

    ElMessage.success('CSRF Token已生成')
}

/**
* 验证CSRF Token
* @description 验证当前Token的有效性
*/
const validateCSRFToken = () => {
    if (!currentCSRFToken.value) {
        csrfResult.type = 'error'
        csrfResult.message = '没有可验证的Token'
        return
    }

    const isValid = csrfProtection.validateToken(currentCSRFToken.value)
    isTokenValid.value = isValid

    if (isValid) {
        csrfResult.type = 'success'
        csrfResult.message = 'CSRF Token验证成功'
        ElMessage.success('Token验证成功')
    } else {
        csrfResult.type = 'error'
        csrfResult.message = 'CSRF Token验证失败或已过期'
        ElMessage.error('Token验证失败')
    }
}

/**
* 清除CSRF Token
* @description 清除当前的CSRF Token
*/
const clearCSRFToken = () => {
    csrfProtection.clearToken()
    currentCSRFToken.value = ''
    isTokenValid.value = false
    tokenExpiry.value = ''

    csrfResult.type = 'info'
    csrfResult.message = 'CSRF Token已清除'

    ElMessage.info('Token已清除')
}

/**
* 验证用户名
* @description 验证用户名输入
*/
const validateUsername = () => {
    const result = validateField(validationInputs.username, 'username')
    usernameValid.value = result.isValid
    usernameMessage.value = result.message
}

/**
* 验证邮箱
* @description 验证邮箱输入
*/
const validateEmail = () => {
    const result = validateField(validationInputs.email, 'email')
    emailValid.value = result.isValid
    emailMessage.value = result.message
}

/**
* 验证密码
* @description 验证密码输入
*/
const validatePassword = () => {
    const result = validateField(validationInputs.password, 'password')
    passwordValid.value = result.isValid
    passwordMessage.value = result.message
}

/**
* 验证URL
* @description 验证URL输入
*/
const validateUrl = () => {
    const result = validateField(validationInputs.url, 'website')
    urlValid.value = result.isValid
    urlMessage.value = result.message
}

/**
* 生成随机字符串
* @description 生成安全的随机字符串
*/
const generateRandom = () => {
    secureRandom.value = generateSecureRandom(16)
}

/**
* 检查文件名
* @description 对文件名进行安全检查
*/
const checkFilename = () => {
    safeFilename.value = getSafeFilename(filenameInput.value)
}

/**
* 解析JSON
* @description 安全解析JSON字符串
*/
const parseJson = () => {
    if (!jsonInput.value) {
        jsonResult.value = '请输入JSON字符串'
        return
    }

    const result = safeJsonParse(jsonInput.value)
    if (result) {
        jsonResult.value = '解析成功: ' + JSON.stringify(result, null, 2)
    } else {
        jsonResult.value = 'JSON格式错误，解析失败'
    }
}

/**
* 页面初始化
* @description 页面加载时的初始化操作
*/
onMounted(() => {
    // 初始化XSS演示
    handleXSSInput()

    // 初始化CSRF Token
    const token = csrfProtection.getToken()
    if (token) {
        currentCSRFToken.value = token
        isTokenValid.value = true
        const expiry = localStorage.getItem('csrf_token_expiry')
        if (expiry) {
            tokenExpiry.value = new Date(parseInt(expiry)).toLocaleString()
        }
    }

    // 生成初始随机字符串
    generateRandom()

    ElMessage.success('安全防护演示页面已加载')
})
</script>

<style scoped lang="scss">
// 导入安全防护页面样式
@use '../assets/styles/tests/_security';
</style>